<?php
/**
 * Created by PhpStorm.
 * User: C。
 * Date: 2019/8/13
 * Time: 9:04
 */
namespace app\home\controller;

use app\common\model\GoodsIlike as GoodsIlikeModel;
use app\common\model\GoodsOption as GoodsOptionModel;

/**
 * 禅旅收藏
 * Class GoodsIlike
 * @package app\home\controller
 */
class GoodsIlike extends Base
{
    /**
     * [getIndex  列表]
     * @param
     * @return json
     * @author [C。]
     */
    public function getIndex()
    {
        $param = input('param.');
        $model = new GoodsIlikeModel();
        $gpmodel = new GoodsOptionModel();
        $this->getPageAndSize($param);
        $mem = $this->user;
        $map = [];
        try{
            $map['gi.status'] = 1;
            $map['gi.memid'] = $mem['id'];
            $count = $model->getCount($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $model->getList($map,$this->from, $this->size);
            foreach($lists as &$v){
                $option = $gpmodel->getMin(['goodsid'=>$v['id'],'status'=>1]);
                $v['price'] = number_format($option,2);
                $v['cover'] = explode(',',$v['cover']);
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
    /**
     * [postAdd  添加]
     * @param
     * @return json
     * @author [C。]
     */
    public function postAdd()
    {
        $gmodel = new GoodsIlikeModel();
        $param = input('param.');
        $user = $this->user;
        try{
            $ilike = $gmodel->findOne(['memid'=>$user['id'],'goodsid'=>$param['goodsid']],'id');
            if($param['status'] == 1){
                if(!empty($ilike)){
                    $gmodel->editData(['status'=>1,'id'=>$ilike['id']]);
                }else{
                    $param['memid'] = $user['id'];
                    $gmodel->addData($param);
                }
            }elseif($param['status'] == 2){
                $gmodel->editData(['status'=>2,'id'=>$ilike['id']]);
                return admin_json(1, '取消收藏成功');
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '失败'.$e->getMessage());
        }
        return admin_json(1, '收藏成功');
    }
}